<?php

class openapi_response {

    function __construct() {
        $this->format = kernel::single('openapi_format_abstract');
    }

    public function send_result($data, $charset, $type, $root = 'response') {
        $res = array(
            $root => $data
        );
        $this->format->process($res, $charset, $type);
    }

    public function send_error($code, $charset, $type, $sub_msg = '', $params) {
        $error_arr = openapi_errorcode::get($code);
        $res = array(
            'error_response' => array(
                'code' => $error_arr['code'],
                'msg' => $error_arr['msg'],
                'sub_msg' => $sub_msg
            )
        );
        if (in_array($error_arr['code'], array(
            'e000001',
            'e000002',
            'e000003',
            'e000004',
            'e000005',
            'e000006',
            'e000007'
        ))) {
            kernel::single('openapi_log')->response($params['method'], md5(time() . rand(1000, 9999)), $params, $res, $params['flag'], false, '失败', '');
        }
        $this->format->process($res, $charset, $type);
    }

    public function getFormatType($type) {
        if (in_array($type, $this->format->type_lists)) {
            return $type;
        } else {
            return '';
        }
    }

    public function getFormatCharset($charset) {
        if (in_array($charset, $this->format->charset_lists)) {
            return $charset;
        } else {
            return '';
        }
    }
}